package org.example.demo3.server.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.demo3.common.exception.RoomNotFoundException;
import org.example.demo3.common.exception.RoomOpenTooMuchException;
import org.example.demo3.common.exception.RoomTooMuchException;
import org.example.demo3.common.result.PageResult;
import org.example.demo3.pojo.dto.RoomPageQueryDTO;
import org.example.demo3.pojo.dto.RoomRegisterDTO;
import org.example.demo3.pojo.entity.Room;
import org.example.demo3.pojo.vo.RoomVO;
import org.example.demo3.server.mapper.RoomMapper;
import org.example.demo3.server.service.ChatRoomMessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class ChatRoomMessageServiceImpl implements ChatRoomMessageService {

    @Autowired
    private RoomMapper roomMapper;

    /**
     * 房间注册
     * @param roomRegisterDTO
     */
    public void roomRegister(RoomRegisterDTO roomRegisterDTO){
        String hostName=roomRegisterDTO.getHostName();
        Integer count=roomMapper.queryRoomCountByHostName(hostName);
        if(count>=5){
            throw new RoomTooMuchException("房间最多创建5个噢！");
        }
        Room room=new Room();
        BeanUtils.copyProperties(roomRegisterDTO,room);
        room.setCreateTime(LocalDateTime.now());
        String code = UUID.randomUUID().toString().substring(0, 8);
        room.setRoomId(code);
        room.setStatus(0);

        roomMapper.insertRoom(room);
    }

    /**
     * 房间查询
     * @param roomPageQueryDTO
     * @return
     */
    public PageResult roomPageQuery(RoomPageQueryDTO roomPageQueryDTO){
        PageHelper.startPage(roomPageQueryDTO.getPage(),roomPageQueryDTO.getPageSize());
        Page<RoomVO> page=roomMapper.queryRoom(roomPageQueryDTO);
        long total=page.getTotal();
        List<RoomVO> records=page.getResult();
        PageResult pageResult=new PageResult(total,records);
        return pageResult;
    }

    /**
     * 更新状态
     * @param status
     * @param roomId
     */
    public void roomStatusUpdate(Integer status, String roomId, String hostName){
        Room room=roomMapper.queryById(roomId);
        if(room == null){
            throw new RoomNotFoundException("未找到该房间！");
        }

        if(roomMapper.queryRoomStatusByHostname(hostName)==1 && status==1){
            throw new RoomOpenTooMuchException("一次只能开启一个房间噢！");
        }
        roomMapper.updateStatusById(status,roomId);
        return;
    }

    /**
     * 房间名查询
     * @param roomId
     * @return
     */
    public RoomVO roomNameQuery(String roomId){
        return roomMapper.queryRoomById(roomId);
    }

     /**
     * 房间删除
     * @param roomId
     */
    public void roomDelete(String roomId){
        roomMapper.roomDelete(roomId);
    }


}
